package nix.mall.cart.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import nix.mall.common.pojo.NixMallResult;
import nix.mall.pojo.Item;
import nix.mall.service.ItemService;
import nix.mall.utils.CookieUtils;
import nix.mall.utils.JsonUtils;

/**
 * 购物车Controller
 */
@Controller
public class CartController {

	@Autowired
	private ItemService itemService;
	
	@Value("${CART_KEY}")
	private String CART_KEY;
	
	@Value("${CART_EXPIRE}")
	private Integer CART_EXPIRE;
	
	@RequestMapping("/cart/add/{itemId}")
	public String addCart(@PathVariable Long itemId, @RequestParam(defaultValue="1") Integer num,
			HttpServletRequest request, HttpServletResponse response) {
		// 向购物车添加商品
		saveOrUpdateCartItem(itemId, num, request, response);
		// 返回添加成功
		return "cartSuccess";
	}
	
	private List<Item> getCartItemList(HttpServletRequest request) {
		// 从Cookie中取购物车商品列表
		String json = CookieUtils.getCookieValue(request, CART_KEY, true);
		if (StringUtils.isBlank(json)) {
			return new ArrayList<>();
		}
		List<Item> list = JsonUtils.jsonToList(json, Item.class);
		return list;
	}
	
	@RequestMapping("/cart/cart")
	public String showCartList(HttpServletRequest request, Model model) {
		// 从Cookie中取购物车列表
		List<Item> cartItemList = getCartItemList(request);
		// 传递至jsp
		model.addAttribute("cartList", cartItemList);
		// 返回
		return "cart";
	}
	
	@RequestMapping("/cart/update/num/{itemId}/{num}")
	@ResponseBody
	public NixMallResult updateItemNum(@PathVariable Long itemId, @PathVariable Integer num,
			HttpServletRequest request, HttpServletResponse response) {
		// 更新购物车商品数量
		saveOrUpdateCartItem(itemId, num, request, response);	
		// 返回成功
		return NixMallResult.ok();
	}
	
	private void saveOrUpdateCartItem(Long itemId, Integer num,
			HttpServletRequest request, HttpServletResponse response) {
		// 从Cookie中取购物车列表
		List<Item> cartItemList = getCartItemList(request);
		// 判断该商品是否存在
		boolean flag = false;
		// 查询对应商品
		for (Item item : cartItemList) {
			if (item.getId() == itemId.longValue()) {
				// 更新商品数量
				item.setNum(num);
				flag = true;
				break;
			}
		}
		// 不存在，添加商品信息
		if (!flag) {
			Item item = itemService.getItemById(itemId);
			// 设置数量（使用商品信息pojo的库存属性，保存数量）
			item.setNum(num);
			// 取一张图片
			String image = item.getImage();
			if (StringUtils.isNoneBlank(image)) {
				String[] images = image.split(",");
				item.setImage(images[0]);
			}
			// 添加至购物车
			cartItemList.add(item);
		}
		// 购物车列表写入Cookie
		CookieUtils.setCookie(request, response, CART_KEY, JsonUtils.objectToJson(cartItemList), CART_EXPIRE, true);
	}
	
	@RequestMapping("/cart/delete/{itemId}")
	public String deleteCartItem(@PathVariable Long itemId, HttpServletRequest request, HttpServletResponse response) {
		// 从Cookie中取出购物车列表
		List<Item> cartItemList = getCartItemList(request);
		// 找到对应商品
		for (Item item : cartItemList) {
			if (item.getId() == itemId.longValue()) {
				// 删除
				cartItemList.remove(item);
				break;
			}
		}		
		// 购物车列表写入Cookie
		CookieUtils.setCookie(request, response, CART_KEY, JsonUtils.objectToJson(cartItemList), CART_EXPIRE, true);
		// 重定向到购物车列表页
		return "redirect:/cart/cart.html";
	}
}
